'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Input } from '@/components/ui/input'
import { canEditByRole, getPermissionDescription, getAllowedDataSources } from '@/lib/data-entry-permissions'
import { ArrowLeft, Save, Lock, Unlock } from 'lucide-react'
import Link from 'next/link'

// 模拟参数表数据
const mockParameterData = [
  { id: 1, name: '设备名称', value: '离心泵001', dataSource: 'E', type: 'text' },
  { id: 2, name: '制造商', value: '某制造商', dataSource: 'P', type: 'text' },
  { id: 3, name: '型号', value: 'MODEL-123', dataSource: 'P', type: 'text' },
  { id: 4, name: '安装日期', value: '2024-01-15', dataSource: 'C', type: 'date' },
  { id: 5, name: '建设状态', value: '已完成', dataSource: 'O', type: 'text' },
  { id: 6, name: '维护记录', value: '定期维护', dataSource: 'R', type: 'text' },
  { id: 7, name: '设计功率', value: '15kW', dataSource: 'E', type: 'text' },
  { id: 8, name: '采购价格', value: '50000元', dataSource: 'P', type: 'text' },
  { id: 9, name: '施工负责人', value: '张工', dataSource: 'C', type: 'text' },
  { id: 10, name: '运行状态', value: '正常', dataSource: 'R', type: 'text' }
]

export default function DataEntryDemoPage() {
  const [currentUserRole, setCurrentUserRole] = useState<string>('admin')
  const [isLocked, setIsLocked] = useState(true)
  const [inputData, setInputData] = useState<Record<number, string>>({})
  const [savedData, setSavedData] = useState<Record<number, string>>({})

  // 初始化数据
  useEffect(() => {
    const initialData: Record<number, string> = {}
    mockParameterData.forEach(item => {
      initialData[item.id] = item.value
    })
    setSavedData(initialData)
    setInputData(initialData)
  }, [])

  // 处理输入变化
  const handleInputChange = (id: number, value: string) => {
    setInputData(prev => ({
      ...prev,
      [id]: value
    }))
  }

  // 保存数据
  const saveData = () => {
    setSavedData({ ...inputData })
    setIsLocked(true)
  }

  // 取消编辑
  const cancelEdit = () => {
    setInputData({ ...savedData })
    setIsLocked(true)
  }

  // 开启编辑
  const enableEdit = () => {
    setInputData({ ...savedData })
    setIsLocked(false)
  }

  // 获取数据来源标签颜色
  const getDataSourceBadgeColor = (dataSource: string) => {
    switch (dataSource) {
      case 'E': return 'bg-blue-500'
      case 'P': return 'bg-green-500'
      case 'C': return 'bg-orange-500'
      case 'O': return 'bg-purple-500'
      case 'R': return 'bg-red-500'
      default: return 'bg-gray-500'
    }
  }

  // 获取数据来源描述
  const getDataSourceDescription = (dataSource: string) => {
    switch (dataSource) {
      case 'E': return '设计阶段数据'
      case 'P': return '采购阶段数据'
      case 'C': return '施工数据'
      case 'O': return '建设数据'
      case 'R': return '运维记录数据'
      default: return '未知来源'
    }
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto py-8">
        {/* 页面头部 */}
        <div className="mb-8">
          <div className="flex items-center gap-4 mb-4">
            <Link href="/">
              <Button variant="outline" className="flex items-center gap-2">
                <ArrowLeft className="h-4 w-4" />
                返回首页
              </Button>
            </Link>
            <h1 className="text-3xl font-bold text-primary">
              数据录入权限演示
            </h1>
          </div>
          <p className="text-muted-foreground">
            演示不同用户角色的数据录入权限控制功能
          </p>
        </div>

        {/* 用户角色选择 */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>用户角色切换</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-4">
              <Select value={currentUserRole} onValueChange={setCurrentUserRole}>
                <SelectTrigger className="w-48">
                  <SelectValue placeholder="选择用户角色" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="admin">管理员</SelectItem>
                  <SelectItem value="designer">设计用户</SelectItem>
                  <SelectItem value="procurement">采购用户</SelectItem>
                  <SelectItem value="construction">施工用户</SelectItem>
                </SelectContent>
              </Select>
              <Badge variant="outline" className="text-sm">
                {getPermissionDescription(currentUserRole)}
              </Badge>
              <div className="flex items-center gap-2 ml-auto">
                {!isLocked ? (
                  <>
                    <Button onClick={cancelEdit} variant="outline">取消</Button>
                    <Button onClick={saveData} className="bg-blue-600 hover:bg-blue-700">
                      <Save className="h-4 w-4 mr-2" />
                      保存
                    </Button>
                  </>
                ) : (
                  <Button onClick={enableEdit} className="bg-blue-600 hover:bg-blue-700">
                    <Unlock className="h-4 w-4 mr-2" />
                    编辑
                  </Button>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 权限说明 */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>权限说明</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
              <div className="text-center">
                <Badge className="bg-blue-500 mb-2">E</Badge>
                <p className="text-sm">设计阶段数据</p>
                <p className="text-xs text-muted-foreground">设计用户可录入</p>
              </div>
              <div className="text-center">
                <Badge className="bg-green-500 mb-2">P</Badge>
                <p className="text-sm">采购阶段数据</p>
                <p className="text-xs text-muted-foreground">采购用户可录入</p>
              </div>
              <div className="text-center">
                <Badge className="bg-orange-500 mb-2">C</Badge>
                <p className="text-sm">施工数据</p>
                <p className="text-xs text-muted-foreground">施工用户可录入</p>
              </div>
              <div className="text-center">
                <Badge className="bg-purple-500 mb-2">O</Badge>
                <p className="text-sm">建设数据</p>
                <p className="text-xs text-muted-foreground">施工用户可录入</p>
              </div>
              <div className="text-center">
                <Badge className="bg-red-500 mb-2">R</Badge>
                <p className="text-sm">运维记录数据</p>
                <p className="text-xs text-muted-foreground">施工用户可录入</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 参数表 */}
        <Card>
          <CardHeader>
            <CardTitle>设备参数表</CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>参数名称</TableHead>
                  <TableHead>数据来源</TableHead>
                  <TableHead>参数值</TableHead>
                  <TableHead>权限状态</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {mockParameterData.map((item) => {
                  const canEdit = canEditByRole(currentUserRole, item.dataSource)
                  const isDisabled = isLocked || !canEdit
                  
                  return (
                    <TableRow key={item.id}>
                      <TableCell className="font-medium">{item.name}</TableCell>
                      <TableCell>
                        <Badge className={getDataSourceBadgeColor(item.dataSource)}>
                          {item.dataSource}
                        </Badge>
                        <div className="text-xs text-muted-foreground mt-1">
                          {getDataSourceDescription(item.dataSource)}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Input
                          value={inputData[item.id] || ''}
                          onChange={(e) => handleInputChange(item.id, e.target.value)}
                          disabled={isDisabled}
                          className={isDisabled ? 'bg-gray-100 cursor-not-allowed' : ''}
                        />
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {isLocked ? (
                            <Lock className="h-4 w-4 text-gray-400" />
                          ) : canEdit ? (
                            <Unlock className="h-4 w-4 text-green-600" />
                          ) : (
                            <Lock className="h-4 w-4 text-red-600" />
                          )}
                          <span className={`text-xs ${canEdit ? 'text-green-600' : 'text-red-600'}`}>
                            {canEdit ? '可编辑' : '无权限'}
                          </span>
                        </div>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
